package com.v1.video.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.AboutIdeaActivity;
import com.v1.video.activity.AboutUserProtocolActivity;
import com.v1.video.activity.MyLoginSubscribeActivity;
import com.v1.video.activity.MyLoginVideoActivity;
import com.v1.video.activity.PersonInfoActivity;
import com.v1.video.activity.SettingLoginActivity;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.MyCenterInfo;
import com.v1.video.domain.MyloginVideoCountEntity;
import com.v1.video.domain.OptionInfo;
import com.v1.video.domain.SetHead;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Logger;
import com.v1.video.widgets.MyDialog;

import java.io.File;

public class MainPageMyFragement2 extends V1BaseFragment {
	private boolean mIsDestory = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.i("fragment", "MainPageDiscoveryFragment-onCreate");
		mIsDestory = false;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("fragment", "MainPageDiscoveryFragment-onDestroy");
		mIsDestory = true;
		// if(taskMessage != null){//ft_12.22消息红点不要了，因为我的页里面的那两个不要了；
		// taskMessage.cancel(true);
		// }
	}

	private final String TAG = "MainPageMyFragement";

	private View rootView;

	private RelativeLayout layoutUserInfo = null;
	// private RelativeLayout layoutUserMsg = null;
	// private LinearLayout layoutUserAddFriend = null;
	/** 我的专辑 */
	// private RelativeLayout layoutUserAlbum = null;
	private RelativeLayout layoutUserShouyi = null;
	/** 设置 */
	private RelativeLayout layoutUserSetup = null;
	/** 好友动态 */
	private RelativeLayout layoutUserFriendMsg = null;
	
	/** 意见反馈 */
	private RelativeLayout layoutUserSuggestion = null;

	private TextView txtVideoNum = null;
	private TextView txtCollectNum = null;
	private TextView txtAttentionNum = null;
	private TextView txtFansNum = null;

	private ImageView userHead = null;
	private TextView txtUserName = null;
	private TextView txtUserDes = null;
	private ImageView userLevel = null;// V认证
	private ImageView userSex = null;
	private ImageView userBack = null;

	// private RelativeLayout messLayoutCount = null;//消息红点背景
	// private TextView messTxtCount = null;//消息红点数据
	private boolean isFirstLoad = true;// 是否首次加载
	// private GetMessageDataAsync taskMessage =
	// null;//ft_12.22消息红点不要了，因为我的页里面的那两个不要了；
	// private RelativeLayout mLayout_UnLogin;
	// private RelativeLayout mLayout_Login;

	private View clear_cache;

	private View ll_autoplay;

	private View mylogin_suggestion_bg;

	private View about_us;
	public static boolean isClearMemory = false;

	private TextView tv_cache;

	private View user_xieyi;

	private ImageView iv_autopaly;


	private boolean isAutoplay;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		rootView = inflater.inflate(R.layout.activity_my_mylogin2, container,
				false);
		initView();
		initData();
		setListener();
		return rootView;
	}

	private void initView() {
		MobclickAgent.onEvent(this.getActivity(), Constant.MY_ID);
		layoutUserInfo = (RelativeLayout) rootView
				.findViewById(R.id.mylogin_user_info_bg);
		layoutUserSuggestion = (RelativeLayout) rootView
				.findViewById(R.id.mylogin_suggestion_bg);

		txtVideoNum = (TextView) rootView
				.findViewById(R.id.mylogin_user_video_num);
		txtCollectNum = (TextView) rootView
				.findViewById(R.id.mylogin_user_collect_num);
		txtAttentionNum = (TextView) rootView
				.findViewById(R.id.mylogin_user_attention_num);

		userHead = (ImageView) rootView
				.findViewById(R.id.mylogin_user_head_img);
		txtUserName = (TextView) rootView
				.findViewById(R.id.mylogin_user_nickname);
		txtUserDes = (TextView) rootView
				.findViewById(R.id.mylogin_user_description);

		userLevel = (ImageView) rootView.findViewById(R.id.iv_user_level);
		userSex = (ImageView) rootView.findViewById(R.id.iv_sex);
		userBack = (ImageView) rootView
				.findViewById(R.id.mylogin_user_back_img);
		clear_cache = rootView.findViewById(R.id.clear_cache);
		ll_autoplay = rootView.findViewById(R.id.ll_autoplay);
		mylogin_suggestion_bg = rootView.findViewById(R.id.mylogin_suggestion_bg);
		about_us = rootView.findViewById(R.id.about_us);
		user_xieyi = rootView.findViewById(R.id.user_xieyi);
		tv_cache = (TextView) rootView.findViewById(R.id.tv_cache);
		iv_autopaly = (ImageView) rootView.findViewById(R.id.iv_autopaly);
	}

	private void initData() {
		isAutoplay = OptionInfo.getInstance(getActivity()).isVideoDetailPageAutoPlay();
		if(isAutoplay){
			iv_autopaly.setImageResource(R.drawable.label_open);
		}else{
			iv_autopaly.setImageResource(R.drawable.label_close);
		}
		getMemorySize();

	}
	
	/**
	 * 获取缓存大小
	 */
	private void getMemorySize() {
		long fileSize = 0;
		String cacheSize = "0KB";
		File filesPicDir = new File(
				android.os.Environment.getExternalStorageDirectory(),
				"Android/data/com.v1.video/cache");
		File cacheDir = getActivity().getCacheDir();
		fileSize += getDirSize(filesPicDir);
		fileSize += getDirSize(cacheDir);
		if (fileSize > 0) {
			cacheSize = formatFileSize(fileSize);
		}
		tv_cache.setText(cacheSize);
	}
	
	 /**
		 * 转换文件大小
		 * 
		 * @param fileS
		 * @return B/KB/MB/GB
		 */
		private String formatFileSize(long fileS) {
			java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
			String fileSizeString = "";
			if (fileS < 1024) {
				fileSizeString = df.format((double) fileS) + "B";
			} else if (fileS < 1048576) {
				fileSizeString = df.format((double) fileS / 1024) + "KB";
			} else if (fileS < 1073741824) {
				fileSizeString = df.format((double) fileS / 1048576) + "MB";
			} else {
				fileSizeString = df.format((double) fileS / 1073741824) + "G";
			}
			return fileSizeString;
		}

		/**
		 * 获取目录文件大小
		 * 
		 * @param dir
		 * @return
		 */
		private long getDirSize(File dir) {
			if (dir == null) {
				return 0;
			}
			if (!dir.isDirectory()) {
				return 0;
			}
			long dirSize = 0;
			File[] files = dir.listFiles();
			for (File file : files) {
				if (file.isFile()) {
					dirSize += file.length();
				} else if (file.isDirectory()) {
					dirSize += file.length();
					dirSize += getDirSize(file); // 递归调用继续统计
				}
			}
			return dirSize;
		}

	public void initDataOfResume() {
//		if (AppContext.getHeadBitmap() != null) {
//			userHead.setImageBitmap(Utils.toRoundBitmap(AppContext
//					.getHeadBitmap()));
//		} else {
			SetHead setHead = new SetHead();
			setHead.setHead(LoginInfo.getInstance().getUserImg(), LoginInfo
					.getInstance().getSex(), userHead);
//		}
		if (LoginInfo.getInstance().getSex().equals("女")) {
			userSex.setImageResource(R.drawable.icon_sex_woman);
		} else {
			userSex.setImageResource(R.drawable.icon_sex_man);
		}
		if (TextUtils.isEmpty(LoginInfo.getInstance().getNickName())
				|| LoginInfo.getInstance().getNickName().equals("null")) {
			txtUserName.setText(LoginInfo.getInstance().getUserName());
		} else {
			txtUserName.setText(LoginInfo.getInstance().getNickName());
		}
		setTextDetail(LoginInfo.getInstance().getDetail());
		if (LoginInfo.getInstance().getIsCertification().equals("1")) {
			userLevel.setVisibility(View.VISIBLE);
		} else {
			userLevel.setVisibility(View.GONE);
		}

		ImageLoader.getInstance().displayImage(
				LoginInfo.getInstance().getUserBackImg(), userBack,
				Constant.PERSONAL_HOME_OPTION, null);
		if (LoginInfo.getInstance().isLogin()) {
//			new GetDataAsync().execute();
			getUserCountInfo(getActivity(),0);
			getUserCountInfo(getActivity(),1);
			getUserCountInfo(getActivity(),2);
			getUserCountInfo(getActivity(),3);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("我的");
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart("我的");
		if (LoginInfo.getInstance().isLogin()) {
			userSex.setVisibility(View.VISIBLE);
			userLevel.setVisibility(View.VISIBLE);
			initData();
			initDataOfResume();

		} else {
			userSex.setVisibility(View.GONE);
			userLevel.setVisibility(View.GONE);
			txtUserName.setText(getResources().getString(
					R.string.main_my_unlogin_tologin));
			txtUserDes.setText(getResources().getString(
					R.string.main_my_unlogin_tologin_tips));
			userHead.setImageResource(R.drawable.anonymous_avatar);
			txtCollectNum.setText("0");
//			txtFansNum.setText("0");
			txtVideoNum.setText("0");
			txtAttentionNum.setText("0");
			userBack.setImageResource(R.drawable.user_unlogin_bg);
		}
		
		isAutoplay = OptionInfo.getInstance(getActivity()).isVideoDetailPageAutoPlay();
		if(isAutoplay){
			iv_autopaly.setImageResource(R.drawable.label_open);
		}else{
			iv_autopaly.setImageResource(R.drawable.label_close);
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
	}

	private void setListener() {
		layoutUserSuggestion.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(getActivity(), AboutIdeaActivity.class);
//				intent.setClass(getActivity(), VideoPlayerVRActivity.class);
//				ArrayList<String> listUrl = new ArrayList<String>();
//				
//				String url = "http://f04.v1.cn/site/14318177.mp4";
//				listUrl.add(url);
//				intent.putStringArrayListExtra("videourl", listUrl);
//				intent.putExtra("pos", 0);
				startActivity(intent);
			}
		});
		
		rootView.findViewById(R.id.lay_video).setOnClickListener(// 视频
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!LoginInfo.getInstance().isLogin()) {
							login();
						} else {
							Intent intent = new Intent();
							intent.setClass(v.getContext(),
									MyLoginVideoActivity.class);
							intent.putExtra("title", "视频");
							startActivity(intent);
						}
					}
				});
		rootView.findViewById(R.id.lay_collect).setOnClickListener(// 收藏
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!LoginInfo.getInstance().isLogin()) {
							login();
						} else {
							Intent intent = new Intent();
							// intent.setClass(v.getContext(),
							// PersonalHomeActivity.class);
							// intent.putExtra("flag",
							// Constant.PERSONAL_COLLECT_FLAG);
							intent.setClass(v.getContext(),
									MyLoginVideoActivity.class);
							intent.putExtra("title", "收藏");
							intent.putExtra(MyLoginVideoActivity.strFlag,
									MyLoginVideoActivity.FLAG_VIDEO_COLLECT);
							startActivity(intent);
						}
					}
				});
		rootView.findViewById(R.id.lay_attention).setOnClickListener(// 订阅
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!LoginInfo.getInstance().isLogin()) {
							login();
						} else {
							Intent intent = new Intent();
							// intent.setClass(v.getContext(),
							// PersonalHomeActivity.class);
							// intent.putExtra("flag",
							// Constant.PERSONAL_ATTENTION_FLAG);
							intent.setClass(v.getContext(),
									MyLoginSubscribeActivity.class);
							intent.putExtra("title", "订阅");
							intent.putExtra(MyLoginSubscribeActivity.strFlag, MyLoginSubscribeActivity.FLAG_SUBSCRIBE);
							startActivity(intent);
						}
					}
				});
//		
		rootView.findViewById(R.id.mylogin_user_head_img).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (!LoginInfo.getInstance().isLogin()) {
							login();
						} else {
							Intent inpersonal = new Intent();
							inpersonal.setClass(getActivity(),
									PersonInfoActivity.class);
							startActivity(inpersonal);
						}
					}
				});
		
		clear_cache.setOnClickListener(new OnClickListener() {
        	
            @Override
            public void onClick(View arg0) {
                if(!isClearMemory){
                	showClearCacheLayout();
                }else{
                	
                }
            }
        });
		
		about_us.setOnClickListener(new OnClickListener() {
        	
            @Override
            public void onClick(View arg0) {
            	Intent intent = new Intent();
                intent.setClass(getActivity(), AboutUserProtocolActivity.class);
                intent.putExtra("link", "http://static.v1.cn/about/pages/aboutUs.html");
                intent.putExtra("activity", "about_us");
                startActivity(intent);
            }
        });
		
		user_xieyi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setClass(getActivity(), AboutUserProtocolActivity.class);
                intent.putExtra("link", "http://static.v1.cn/v1cn/app5.0/userProtocol.html");
                intent.putExtra("activity", "user_xieyi");
                startActivity(intent);
            }
        });
		
		ll_autoplay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
            	if(isAutoplay){
            		isAutoplay = false;
            		iv_autopaly.setImageResource(R.drawable.label_close);
            		OptionInfo.getInstance(getActivity()).setVideoDetailPageAutoPlay(false);
            		OptionInfo.getInstance(getActivity()).saveData(getActivity());
            	}else{
            		isAutoplay = true;
            		iv_autopaly.setImageResource(R.drawable.label_open);
            		OptionInfo.getInstance(getActivity()).setVideoDetailPageAutoPlay(true);
            		OptionInfo.getInstance(getActivity()).saveData(getActivity());
            	}
            }
		});
	}
	
	
	 private void showClearCacheLayout() {
			final MyDialog dialogCommon = new MyDialog(getActivity(),
					R.style.dialog_headsetting);
			LinearLayout linearlayout;
			android.view.WindowManager.LayoutParams layoutparams;
			linearlayout = (LinearLayout) ((LayoutInflater) getActivity()
					.getSystemService("layout_inflater")).inflate(
					R.layout.dialog_memory_clear, null);
			linearlayout.setMinimumWidth(10000);

			layoutparams = dialogCommon.getWindow().getAttributes();
			layoutparams.x = 0;
			layoutparams.y = -1000;
			layoutparams.gravity = 80;
			dialogCommon.onWindowAttributesChanged(layoutparams);

			dialogCommon.setCanceledOnTouchOutside(true);
			dialogCommon.setContentView(linearlayout);
			
			dialogCommon.findViewById(R.id.ll_report).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialogCommon.dismiss();
							ImageLoader.getInstance().getDiscCache().clear();
							ImageLoader.getInstance().getMemoryCache().clear();
							ToastAlone.showToast(getActivity(), "缓存已清理", 1);
							tv_cache.setText("0KB");
							isClearMemory = true;
						}
					});
			dialogCommon.findViewById(R.id.ll_cancel).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialogCommon.dismiss();
						}
					});
			dialogCommon.show();
		}

	private void login() {
		Intent intent_login = new Intent(getActivity(),
				SettingLoginActivity.class);
		intent_login.putExtra("loginFlag", 7);
		startActivityForResult(intent_login, Constant.REQUESTCODE_LOGIN_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constant.REQUESTCODE_LOGIN_CODE:
			if (resultCode == Activity.RESULT_OK) {
				onResume();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void refresh(Object tag) {
		// TODO Auto-generated method stub

	}

	/**
	 * 获取用户视频等相关数据
	 */
	private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {

		private String errorMsg = "";

		// private ProgressDialog pd;
		MyCenterInfo userNumInfo = null;

		public GetDataAsync() {

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// pd =
			// Utils.getProgressDialog(getActivity(),getResources().getString(R.string.get_data),
			// this);
			// pd.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				NetEngine engine = new NetEngine();
				userNumInfo = engine.getMyCenter(LoginInfo.getInstance()
						.getUserId());
				if (userNumInfo == null) {
					errorMsg = "获取数据失败！";
				}
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return false;

		}

		// Uri uri = Uri.parse(versionInfo.url);
		// Intent it = new Intent(Intent.ACTION_VIEW,uri);
		// startActivity(it);
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);

			// if(pd != null && pd.isShowing()){
			// pd.cancel();
			// }

			if (mIsDestory)
				return;

			if (errorMsg.equals("") && userNumInfo != null) {
				if (userNumInfo.getReleaseCounts().equals("")) {
					txtVideoNum.setText("0");
				} else {
					txtVideoNum.setText(userNumInfo.getReleaseCounts());
				}
				if (userNumInfo.getCollectionCounts().equals("")) {
					txtCollectNum.setText("0");
				} else {
					txtCollectNum.setText(userNumInfo.getCollectionCounts());
				}
				if (userNumInfo.getFocusOnCounts().equals("")) {
					txtAttentionNum.setText("0");
				} else {
					txtAttentionNum.setText(userNumInfo.getFocusOnCounts());
				}
				if (userNumInfo.getFansCounts().equals("")) {
//					txtFansNum.setText("0");
				} else {
//					txtFansNum.setText(userNumInfo.getFansCounts());
				}

			} else {
//				ToastAlone.showToast(getActivity(), errorMsg, 1);
			}
		}
	}

	private void setTextDetail(String detail) {

		if (detail != null && !detail.equals("")) {
			// detailStr = detail;
			txtUserDes.setText(detail);
			// txtUserDes.setTextColor(getResources().getColor(R.color.gray_bg));
		} else {
			// detailStr = "";
			txtUserDes.setText("Ta很懒，什么都没说");
			// txtUserDes.setTextColor(getResources().getColor(R.color.dark_gray));
		}

	}	
	
	/**获取用户视频数*/
	public void getUserCountInfo(final Activity context,final int type){
		String url = "";//Constant.GET_USER_VIDEO_COUNT+"&uid="+LoginInfo.getInstance().getUserId()+"&devid="+Constant.DEVICEID;
		if(type == 0){
			url = V1VideoHttpApi.GET_USER_VIDEO_COUNT()+"&uid="+LoginInfo.getInstance().getUserId()+"&devid="+Constant.DEVICEID;
		}else if(type == 1){
			url = V1VideoHttpApi.GET_USER_ATTENTATION_COUNT()+"&uid="+LoginInfo.getInstance().getUserId()+"&devid="+Constant.DEVICEID;
		}else if(type == 2){
			url = V1VideoHttpApi.GET_USER_COLLECT_COUNT()+"&uid="+LoginInfo.getInstance().getUserId()+"&devid="+Constant.DEVICEID;
		}else if(type == 3){
			url = V1VideoHttpApi.GET_USER_FANS_COUNT()+"&uid="+LoginInfo.getInstance().getUserId()+"&devid="+Constant.DEVICEID;
		}
    	Logger.i(TAG, "用户视频数Url ="+url);
		RequestManager.getInstance().getRequest(context, url, null, MyloginVideoCountEntity.class, 0, "MainPageMyFragment", new OnResponseListener(){
			
			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				
				if(object != null){
					MyloginVideoCountEntity entity = (MyloginVideoCountEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
//						ToastAlone.showToast(context, "未知错误", Toast.LENGTH_SHORT);
						return ;
					}else if(!header.getStatus().equals("1")){
//						ToastAlone.showToast(context, header.getMessage(), Toast.LENGTH_SHORT);
						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							
							if(entity.getBody().getData() != null){
								if(type == 0){
									txtVideoNum.setText(entity.getBody().getData());
								}else if(type == 1){
									txtAttentionNum.setText(entity.getBody().getData());
								}else if(type == 2){
									txtCollectNum.setText(entity.getBody().getData());
								}else if(type == 3){
//									txtFansNum.setText(entity.getBody().getData());
								}
							}
							
						}else{
//							toast(header.getMessage());
						}
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				
			}
		});
		
		return ;
	}

}
